      
'use strict';

module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/ttrefund 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			refund_desc,
			refund_fee,
			out_refund_no,
			tt_order_id,
			_add_time,
			_add_time_str,
			appid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
      if (userInfo.username != "admin") {
      	res = { code: 0, msg: '操作失败！非admin账户不能操作退款' };
      	return res;
      }
	  // 查询密钥
	  let A = await vk.baseDao.selects({
	    dbName:"a_appid",
	    // 主表where条件
	    whereJson:{
	      appid:appid
	    },
	  });
	  
	  console.log("A========",A);
	  
	  
	  let appsecret = A.rows[0].appsecret

		//获取token参数
		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key:appid, // id
				client_secret:appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})

		//创建短剧
		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token

		console.log('打印token', access_token);



	
		//获取token参数
		let urlB = 'https://open.douyin.com/api/trade_basic/v1/developer/refund_create/'
		res.ttnewnoce = await uniCloud.httpclient.request(urlB, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				'access-token': access_token,
			},
			data: {
				order_id: tt_order_id,
				out_refund_no: out_refund_no,
				order_entry_schema: {
					path: 'components/rechargelist/rechargelist'
				},
				// item_order_detail: [{
				// 	item_order_id: tt_order_id,
				// 	refund_amount: refund_fee,
				// }, ],
				refund_all:true,
				refund_total_amount: refund_fee,
				refund_reason: [{
					code: 999,
					text: refund_desc
				}],
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})
		
		if(res.ttnewnoce.data.err_no==0){
			
			
			 //修改订单状态为已退款。0：未支付  1：已支付  2：已退款
			 let edit_pay_status = await db.collection('a_recharge').where({ out_trade_no: out_trade_no }).update({
			 	pay_status: 2,
			 	remark: "已退款。退款金额(单位：分)：" + refund_fee || "全额"
			 })
			 
			 // 执行add命令，添加退款操作日志
			 let dbName = "a_log"; // 表名
			 res.id = await vk.baseDao.add({
			 	dbName,
			 	dataJson: {
					out_refund_no:out_refund_no,
					out_trade_no: out_trade_no,
			 		user_id: userInfo._id,
			 		username: userInfo.username,
			 		ip: originalParam.context.CLIENTIP,
			 		osName: originalParam.context.osName,
			 		osVersion: originalParam.context.osVersion,
			 		deviceId: originalParam.context.deviceId,
			 		ua: originalParam.context.ua,
			 		remark: "后台操作退款记录",
			 		_add_time,
			 		_add_time_str
			 	}
			 });
			  res = { code: 0, msg: '退款成功' };
			 
		}else{
			 res = { code: 0, msg: '退款失败' };
		}

	
       


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

    